package cn.cycleif.config;

import cn.cycleif.intercept.PageableItcpt;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * &#064;Date: 24/04/22-17:37
 * &#064;Description:
 */
@Configuration
@RequiredArgsConstructor
public class WebMvcCfg implements WebMvcConfigurer {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new PageableItcpt());
    registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
    registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
            .addPathPatterns("/sys/**");
    // registry.addInterceptor(new GuestIdItcpt())
    //         .addPathPatterns("/api/**");
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/doc.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }

  // 日期格式转换，也可以使用在字段上使用注解
  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    jackson2HttpMessageConverter.setObjectMapper(new JacksonObjectMapper());
    converters.add(converters.size() - 1, jackson2HttpMessageConverter);
  }

  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration               config = new CorsConfiguration();
    config.addAllowedOrigin("*"); // 允许所有来源
    config.addAllowedMethod("*"); // 允许所有HTTP方法
    config.addAllowedHeader("*"); // 允许所有请求头
    source.registerCorsConfiguration("/**", config); // 对所有路径生效
    return new CorsFilter(source);
  }
}
